package com.tanhua.server.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.utils.AppJwtUtil;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.api.RecommendUserApi;

import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.service.TodayBestService;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.RecommendUserQueryParam;
import com.tanhua.server.vo.TodayBest;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;


/**今日佳人功能业务
 * @author ldp
 * @date 2021/4/27 19:00
 */
@Service//非dubbo包下的注解
public class TodayBestServiceImpl implements TodayBestService {

    //远程调用接口
    @Reference(version = "1.0.0") //采用dubbo包下的进行远程调接口
    private RecommendUserApi recommendUserApi;

    @Value("${tanhua.sso.default.user}")
    public String defaultUserId;

    @Autowired
    private UserInfoMapper userInfoMapper;

    /**
     * 1 根据用户id查询推荐的今日佳人信息
     * @param
     * @return
     */
    @Override
    public TodayBest queryTodayBest() {
/*        //1.检验token
        Claims claims = AppJwtUtil.getClaimsBody(token);
        int count = AppJwtUtil.verifyToken(claims);
        if(count==1 || count==2){
            //表示过期了
            return null;
        }if(count==-1 || count==0){}*/
            //在有效期内
            // 2。查询推荐用户（今日佳人）
           User user= UserThreadLocal.get();
            //3.远程调用接口，获取今日佳人
            TodayBest todayBest = queryWithMaxScore(Long.valueOf(user.getId()+ ""));
            //3.1如果为空
            if(todayBest==null){
                //则设置默认的今日佳人
                todayBest=new TodayBest();
                todayBest.setId(Long.valueOf(defaultUserId));
                todayBest.setFateValue(80L);//固定值
               
            }
            //3.2 如果不为空，补全todayBest信息
                //3.2.1 查询userInfo信息
            UserInfo userInfo = userInfoMapper.selectOne(Wrappers.<UserInfo>lambdaQuery().eq(UserInfo::getUserId,todayBest.getId()));
            if(null == userInfo){
                return null;
            }
            //3.2.2 封装数据并返回
            todayBest.setAvatar(userInfo.getLogo());
            todayBest.setNickname(userInfo.getNickName());
            todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));
            todayBest.setGender(userInfo.getSex().getValue()==1? "man":"woman");
            todayBest.setAge(userInfo.getAge());
            return todayBest;


    }


    //抽取获取今日佳人方法
    private TodayBest queryWithMaxScore(Long userId){
        //远程调用最高分今日佳人接口
        RecommendUser recommendUser = recommendUserApi.queryWithMaxScore(userId);
        //非空判断
        if(null == recommendUser){
            return null;
        }
        //数据封装
        TodayBest todayBest=new TodayBest();
        //编号
        todayBest.setId(recommendUser.getUserId());
        //缘分值
        double score = Math.floor(recommendUser.getScore());//取整,98.2 -> 98
        todayBest.setFateValue(Double.valueOf(score).longValue());
        //返回
        return todayBest;
    }

    /**
     * 2----获取推荐列表集合
     * @param
     * @param queryParam 请求参数
     * @return
     */
    @Override
    public PageResult queryRecommendation( RecommendUserQueryParam queryParam) {
/*        //1.检验token
        Claims claims = AppJwtUtil.getClaimsBody(token);
        int count = AppJwtUtil.verifyToken(claims);
        if(count==1 || count==2){
            //表示过期了
            return null;
        }if(count==-1 || count==0){}*/
            //表示在有效期内

            Integer page = queryParam.getPage();
            Integer pagesize = queryParam.getPagesize();

            PageResult pageResult=new PageResult();
            pageResult.setPage(page);
            pageResult.setPagesize(pagesize);


            // 3。获取用户id
            User user= UserThreadLocal.get();

            //2.远程调用获取推荐列表集合
            PageInfo<RecommendUser> recommendUserPageInfo = recommendUserApi.queryPageInfo(Long.valueOf(user.getId() + ""), page, pagesize);
            //4.获取推荐列表
            List<RecommendUser> records = recommendUserPageInfo.getRecords();
            if(CollectionUtils.isEmpty(records)){
                //如果集合为空，则表示没有推荐列表
                return pageResult;
            }
            //否则，集合不为空，则获取被推荐的id进行封装
            Set<Long> userIds=new HashSet();
            for (RecommendUser record : records) {
                userIds.add(record.getUserId());
            }


            //5.根据条件进行查询推荐列表集合
            LambdaQueryWrapper<UserInfo> querwrapper= Wrappers.lambdaQuery();
            //5.1 根据推荐人id去查询
            querwrapper.in(UserInfo::getUserId,userIds);
            //5.2 根据性别查询
            if(StringUtils.isNotEmpty(queryParam.getGender())){
                //querwrapper.eq(UserInfo::getSex,StringUtils.equals(queryParam.getGender(),"man")?1:2);
            }
            //5.3 根据年龄查询,查小于等于
            if(queryParam.getAge()!=null){
                // querwrapper.le(UserInfo::getAge,queryParam.getAge());
            }
            //5.4 根据城市查询
            if(StringUtils.isNotEmpty(queryParam.getCity())){
                // querwrapper.eq(UserInfo::getCity,queryParam.getCity());
            }
            //5.5 根据学历查询
            if(StringUtils.isNotEmpty(queryParam.getEducation())){
                // querwrapper.eq(UserInfo::getEdu,queryParam.getEducation());
            }

            List<UserInfo> userInfos = userInfoMapper.selectList(querwrapper);
            if(CollectionUtils.isEmpty(userInfos)){
                //如果查询集合为空
                return pageResult;
            }
            //否则查询不为空，封装数据
            List<TodayBest> items=new ArrayList<>();

            //6.封装TodayBest数据

            for (UserInfo userInfo : userInfos) {
                TodayBest todayBest=new TodayBest();
                todayBest.setId(userInfo.getUserId());
                todayBest.setAvatar(userInfo.getLogo());
                todayBest.setNickname(userInfo.getNickName());
                todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));
                todayBest.setGender(userInfo.getSex().getValue() == 1 ? "man" : "woman");
                todayBest.setAge(userInfo.getAge());

                //缘分值
                for (RecommendUser record : records) {
                    if(record.getUserId().longValue() == userInfo.getUserId().longValue()){
                        double score = Math.floor(record.getScore());//取整,98.2 -> 98
                        todayBest.setFateValue(Double.valueOf(score).longValue());
                        break;
                    }
                }
                items.add(todayBest);
            }

            //按照缘分值进行倒序排序
            Collections.sort(items, (o1, o2) -> new Long(o2.getFateValue() - o1.getFateValue()).intValue());

            //7.封装PageInfo数据
            pageResult.setItems(items);
            return pageResult;


    }

}